package br.fatec.ads.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.fatec.ads.dao.AreaDAO;
import br.fatec.ads.dao.PerguntaDAO;
import br.fatec.ads.exception.AreaException;
import br.fatec.ads.exception.DataBaseException;
import br.fatec.ads.exception.PerguntaException;
import br.fatec.ads.model.Area;
import br.fatec.ads.model.Pergunta;

public class PerguntaIncluir extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public PerguntaIncluir() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			List listaArea = new ArrayList();
			HttpSession session = request.getSession(false);
			
			Area area = new Area();
			
			AreaDAO areaDAO = new AreaDAO();
		
			listaArea = areaDAO.listarArea(area);
			
			session.setAttribute("listaComboArea", listaArea);
			
			request.getRequestDispatcher("cadpergunta_i.jsp").forward(request, response);
		} catch (AreaException e) {
			e.printStackTrace();
		} catch (DataBaseException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			HttpSession session = request.getSession(false);
			Pergunta pergunta = new Pergunta();
			Area area = new Area();
			
			area.setIdArea(request.getParameter("cmbArea").equals("") ? 0
					: Integer.parseInt(request.getParameter("cmbArea")));
			
			pergunta.setDescPergunta(request.getParameter("txtDescPergunta"));
			pergunta.setTipoPergunta(request.getParameter("cmbTipoPergunta").equals("") ? null
					: request.getParameter("cmbTipoPergunta"));
			pergunta.setObrigatorio(request.getParameter("obrigatorio") == null ? "N" : "S");
			pergunta.setPadrao(request.getParameter("padrao") == null ? "N" : "S");
			pergunta.setArea(area);
			pergunta.setUsuario(session.getAttribute("usuarioDesc").toString());
			
			PerguntaDAO perguntaDAO = new PerguntaDAO();
			
			perguntaDAO.incluirPergunta(pergunta);
			
			request.getRequestDispatcher("PerguntaPesquisar?acao=SUCESSO_INCLUIR").forward(request, response);
		} catch (PerguntaException e) {
			request.getRequestDispatcher("cadpergunta_i.jsp?acao=erro").forward(request, response);
			e.printStackTrace();
		} catch (DataBaseException e) {
			request.getRequestDispatcher("cadpergunta_i.jsp?acao=erro").forward(request, response);
			e.printStackTrace();
		}
	}
}